package com.example.hello.service.impl;

import com.example.hello.mapper.BookMapper;
import com.example.hello.pojo.Book;
import com.example.hello.pojo.PageQueryParam;
import com.example.hello.pojo.PageResult;
import com.example.hello.service.BookRepositoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookRepositoryServiceImpl implements BookRepositoryService {

    @Autowired
    private BookMapper bookMapper;

    /**
     * 查找书籍的所有库存
     * @return
     */
    @Override
    public PageResult<Book> findAll(PageQueryParam bookQueryParam) {
        // 1. 设置分页参数
        PageHelper.startPage(bookQueryParam.getPage(), bookQueryParam.getPageSize());
        // 2. 执行查询
        List<Book> list = bookMapper.findAll(bookQueryParam);
        // 3. 解析查询结果，封装为 PageResult 对象并返回
        Page<Book> p = (Page<Book>) list;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Override
    public PageResult<Book> findAllOrderByBorrowNum(PageQueryParam bookQueryParam) {
        // 1. 设置分页参数
        PageHelper.startPage(bookQueryParam.getPage(), bookQueryParam.getPageSize());
        // 2. 执行查询
        List<Book> list = bookMapper.findAllOrderByBorrowNum(bookQueryParam);
        // 3. 解析查询结果，封装为 PageResult 对象并返回
        Page<Book> p = (Page<Book>) list;
        return new PageResult<>(p.getTotal(), p.getResult());
    }


    @Override
    public void save(Book book) {
        if (book.getSum()==null){
            book.setSum(1);
            book.setLastNum(1);
        }
        if (book.getRecommendNum() == null){
            book.setRecommendNum(0);
        }
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.save(book);
    }

    @Override
    public List<Book> findByTitleOrAuthorOrISBN(String requestParam) {
        List<Book> bookList = bookMapper.findByTitleOrAuthorOrISBN(requestParam);
        return bookList;
    }
}
